﻿using CJiaBao.Core.Utils;
using Core.Configuration.Helper;
using Quartz;
using Quartz.Impl;

namespace Core.Quartz
{
    public class QuartzPro
    {
        private IScheduler scheduler;
        private static ISchedulerFactory factory;
        public QuartzPro()
        {
            if (factory == null)
            {
                factory = CreateFactory();
            }
        }

        /// <summary>
        /// 创建一个调度器
        /// </summary>
        /// <returns></returns>
        private StdSchedulerFactory CreateFactory()
        {
            return new StdSchedulerFactory();
        }

        /// <summary>
        /// 开始加载调动环境
        /// </summary>
        /// <returns></returns>
        public async Task Start()
        {
            try
            {
                scheduler = await factory.GetScheduler();
                if (scheduler.IsStarted)
                {
                    await Log("quartz 无需再次初始化");
                    return;
                }
                //开始调度器
                await scheduler.Start();
                await Log("quertz环境已启动");
            }
            catch (Exception ex)
            {
                await Log($"quartz 初始化异常,{ex.Message}");
            }
        }

        /// <summary>
        /// 停止调度
        /// </summary>
        public void Stop()
        {
            scheduler.Shutdown();
            scheduler = null;
            Log("quertz环境已停止");
        }

        /// <summary>
        /// 创建运行的调度器
        /// </summary>
        /// <param name="jobName">任务唯一名称</param>
        /// <param name="groupName"></param>
        /// <param name="secends">间隔时间</param>
        /// <param name="url">调用的url</param>
        /// <returns></returns>
        public async Task CreateJob<T>(UrlJobInfo jobInfo) where T : IJob
        {
            if (await scheduler.CheckExists(new JobKey(jobInfo.JobName, jobInfo.GroupName)))
            {
                await Log($"任务{jobInfo.JobName}已存在");
                return;
            }

            //创建一个作业
            var job = JobBuilder.Create<T>()
            .WithIdentity(jobInfo.JobName, jobInfo.GroupName)
            .UsingJobData("UrlJobInfo", JsonHelper.ToJson(jobInfo))
            .Build();

            //创建一个触发器
            var tigger = TriggerBuilder.Create()
            .WithIdentity(jobInfo.JobName, jobInfo.GroupName)
            .StartNow()
            //.WithCronSchedule("0/3 * * * * ? ") //3秒后循环执行
            .WithSimpleSchedule(a =>
             {
                 a.RepeatForever();//永远执行
                 a.WithIntervalInSeconds(jobInfo.Seconds);//执行间隔3s
             })
            .Build();

            //把作业和触发器放入调度器中
            await scheduler.ScheduleJob(job, tigger);
        }

        public async Task PauseJob(string jobName, string groupName)
        {
            var jobKey = new JobKey(jobName, groupName);
            if (await scheduler.CheckExists(jobKey))
            {
                await scheduler.PauseJob(jobKey);
                await Log($"{jobName} 已暂停");
            }
            else
            {
                await Log($"任务{jobName}不存在");
            }
        }

        /// <summary>
        /// 恢复
        /// </summary>
        /// <returns></returns>
        public async Task ResumeJob(string jobName, string groupName)
        {
            var jobKey = new JobKey(jobName, groupName);
            if (await scheduler.CheckExists(jobKey))
            {
                await scheduler.ResumeJob(jobKey);
                await Log($"{jobName} 恢复成功");
            }
            else
            {
                await Log($"任务{jobName}不存在");
            }
        }

        private Task Log(string msg)
        {
            Console.WriteLine(msg);
            return LogHelper.WriteAsync("quartz", msg);
        }
    }
}
